package com.bdqn.maven.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.bdqn.maven.dao.UserLogMapper;
import com.bdqn.maven.dao.UserMapper;
import com.bdqn.maven.entity.User;
import com.bdqn.maven.entity.UserLog;
import com.bdqn.maven.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userDao;
    @Autowired
    private UserLogMapper userLogDao; 

    public int add(User user) {
        setPackageInfo(user);
        int result = userDao.insertSelective(user);
        if (result > 0) {
            // 获取注册成功后的用户ID
            User registeredUser = userDao.findByUsernameAndPassword(user.getUsername(), user.getPassword());
            if (registeredUser != null) {
                registeredUser.addLog("注册成功，初始余额: " + registeredUser.getBalance() + "，套餐金额: " + registeredUser.getPackagePrice(registeredUser.getUserpackage()));
                // 假设这里可以添加充值相关日志，如果有充值操作
                if (registeredUser.getBalance() > 0) {
                    registeredUser.addLog("注册时充值 " + registeredUser.getBalance() + " 元");
                }
                saveUserLogs(registeredUser);
            }
        }
        return result;
    }

    public int delete(int id) {
        return userDao.deleteByPrimaryKey(id);
    }

    public int update(User user) {
        User existingUser = userDao.selectByPrimaryKey(user.getId());
        if (existingUser != null) {
            // 如果套餐发生变化，重置套餐对应的基础数据
            if (user.getUserpackage() != null && !user.getUserpackage().equals(existingUser.getUserpackage())) {
                setPackageBaseData(user, user.getUserpackage());
                // 添加套餐变更日志
                existingUser.addLog("套餐变更为: " + user.getUserpackage());
            }

            // 如果传递了短信、流量或通话数据，允许更新
            if (user.getSms() != null) {
                existingUser.setSms(user.getSms());
            }
            if (user.getTraffic() != null) {
                existingUser.setTraffic(user.getTraffic());
            }
            if (user.getBill() != null) {
                existingUser.setBill(user.getBill());
            }

            // 如果传递了余额，更新余额
            if (user.getBalance() != null) {
                existingUser.setBalance(user.getBalance());
            }

            int result = userDao.updateByPrimaryKeySelective(existingUser);
            
            // 保存日志
            if (result > 0 && !existingUser.getLogs().isEmpty()) {
                saveUserLogs(existingUser);
            }
            
            return result;
        }
        return 0;
    }
    // 根据套餐ID设置基础数据
    private void setPackageBaseData(User user, Integer packageId) {
        switch (packageId) {
            case 1:
                user.setSms(20);      // 套餐1: 20条短信
                user.setTraffic(1.0); // 1GB流量
                user.setBill(200.0);  // 200分钟话费
                break;
            case 2:
                user.setSms(0);       // 套餐2: 0条短信
                user.setTraffic(10.0);// 10GB流量
                user.setBill(0.0);    // 0分钟话费
                break;
            case 3:
                user.setSms(50);      // 套餐3: 50条短信
                user.setTraffic(5.0); // 5GB流量
                user.setBill(500.0);  // 500分钟话费
                break;
            default:
                break;
        }
    }



    public User findById(int id) {
        return userDao.selectByPrimaryKey(id);
    }

    public List<User> getAll() {
        return userDao.getAll();
    }

    public User findByUsernameAndPassword(String username, String password) {
        return userDao.findByUsernameAndPassword(username, password);
    }

    private void setPackageInfo(User user) {
        Integer packageId = user.getUserpackage();
        if (packageId != null) {
            switch (packageId) {
                case 1:
                    user.setSms(20);
                    user.setTraffic(1.0);
                    user.setBill(50.0);
                    break;
                case 2:
                    user.setSms(0);
                    user.setTraffic(10.0);
                    user.setBill(60.0);
                    break;
                case 3:
                    user.setSms(50);
                    user.setTraffic(5.0);
                    user.setBill(150.0);
                    break;
                default:
                    break;
            }
        }
    }
    
    // 充值QQ会员
    @Override
    public boolean rechargeQQVip(int id) {
        User user = userDao.selectByPrimaryKey(id);
        if (user != null) {
            if (user.getBalance() >= 10) {
                user.setBalance(user.getBalance() - 10);
                if (userDao.updateByPrimaryKeySelective(user) > 0) {
                    user.addLog("充值QQ会员，花费10元，剩余余额: " + user.getBalance());
                    saveUserLogs(user);
                    return true;
                }
            }
        }
        return false;
    }

    // 发短信
    @Override
    public boolean sendSms(int id) {
        User user = userDao.selectByPrimaryKey(id);
        if (user != null) {
            if (user.getSms() >= 1) {
                user.setSms(user.getSms() - 1);
                if (userDao.updateByPrimaryKeySelective(user) > 0) {
                    user.addLog("发短信，花费1条短信，剩余短信: " + user.getSms());
                    saveUserLogs(user);
                    return true;
                }
            } else if (user.getBalance() >= 1) {
                // 购买1条短信
                user.setSms(user.getSms() + 1 - 1); // 购买1条并使用1条
                user.setBalance(user.getBalance() - 1);
                if (userDao.updateByPrimaryKeySelective(user) > 0) {
                    user.addLog("短信不足，购买1条短信花费1元，剩余余额: " + user.getBalance() + "，剩余短信: " + user.getSms());
                    saveUserLogs(user);
                    return true;
                }
            }
        }
        return false;
    }

    // 打电话
    @Override
    public boolean makeCall(int id) {
        User user = userDao.selectByPrimaryKey(id);
        if (user != null) {
            if (user.getBalance() >= 3) {
                user.setBalance(user.getBalance() - 3);
                // 增加通话时长
                user.setBill(user.getBill() + 1);
                if (userDao.updateByPrimaryKeySelective(user) > 0) {
                    user.addLog("打电话，花费3元，剩余余额: " + user.getBalance() + "，总通话时长: " + user.getBill() + "分钟");
                    saveUserLogs(user);
                    return true;
                }
            }
        }
        return false;
    }

    // 看视频
    @Override
    public boolean watchVideo(int id) {
        User user = userDao.selectByPrimaryKey(id);
        if (user != null) {
            if (user.getTraffic() >= 2) {
                user.setTraffic(user.getTraffic() - 2);
                if (userDao.updateByPrimaryKeySelective(user) > 0) {
                    user.addLog("看视频，花费2GB流量，剩余流量: " + user.getTraffic() + "GB");
                    saveUserLogs(user);
                    return true;
                }
            } else if (user.getBalance() >= 10) {
                // 购买2GB流量
                user.setTraffic(user.getTraffic() + 2 - 2); // 购买2GB并使用2GB
                user.setBalance(user.getBalance() - 10);
                if (userDao.updateByPrimaryKeySelective(user) > 0) {
                    user.addLog("流量不足，购买2GB流量花费10元，剩余余额: " + user.getBalance() + "，剩余流量: " + user.getTraffic() + "GB");
                    saveUserLogs(user);
                    return true;
                }
            }
        }
        return false;
    }

    // 购买短信
    @Override
    public boolean buySms(int id, int count) {
        User user = userDao.selectByPrimaryKey(id);
        if (user != null) {
            double cost = count; // 1元/条
            if (user.getBalance() >= cost) {
                user.setSms(user.getSms() + count);
                user.setBalance(user.getBalance() - cost);
                if (userDao.updateByPrimaryKeySelective(user) > 0) {
                    user.addLog("购买" + count + "条短信，花费" + cost + "元，剩余余额: " + user.getBalance() + "，剩余短信: " + user.getSms());
                    saveUserLogs(user);
                    return true;
                }
            }
        }
        return false;
    }

    // 购买流量
    @Override
    public boolean buyTraffic(int id, double amount) {
        User user = userDao.selectByPrimaryKey(id);
        if (user != null) {
            double cost = amount * 5; // 5元/GB
            if (user.getBalance() >= cost) {
                user.setTraffic(user.getTraffic() + amount);
                user.setBalance(user.getBalance() - cost);
                if (userDao.updateByPrimaryKeySelective(user) > 0) {
                    user.addLog("购买" + amount + "GB流量，花费" + cost + "元，剩余余额: " + user.getBalance() + "，剩余流量: " + user.getTraffic() + "GB");
                    saveUserLogs(user);
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public boolean isPhoneExists(String phone) {
        int count = userDao.checkPhoneExists(phone);
        return count > 0;
    }

    public boolean changePackage(int id, int newPackage) {
        User user = userDao.selectByPrimaryKey(id);
        if (user != null) {
            double packagePrice = user.getPackagePrice(newPackage);
            if (user.getBalance() >= packagePrice) {
                user.setBalance(user.getBalance() - packagePrice);
                user.setUserpackage(newPackage);
                // 根据套餐 ID 设置短信、流量和话费
                switch (newPackage) {
                    case 1:
                        user.setSms(20);
                        user.setTraffic(1.0);
                        user.setBill(200.0); // 修正为200分钟
                        break;
                    case 2:
                        user.setSms(0);
                        user.setTraffic(10.0);
                        user.setBill(0.0);
                        break;
                    case 3:
                        user.setSms(50);
                        user.setTraffic(5.0);
                        user.setBill(500.0);
                        break;
                    default:
                        break;
                }
                if (userDao.updateByPrimaryKeySelective(user) > 0) {
                    user.addLog("套餐更改成功，新套餐金额: " + packagePrice + "，剩余余额: " + user.getBalance());
                    saveUserLogs(user);
                    return true;
                }
            }
        }
        return false;
    }

    public void saveUserLogs(User user) {
        List<String> logs = user.getLogs();
        for (String log : logs) {
            UserLog userLog = new UserLog(user.getId(), log, new Date());
            userLogDao.insert(userLog);
        }
        // 清空用户的临时日志列表，避免重复保存
        user.clearLogs();
    }

    @Override
    public void saveLogToFile(int userId, String filePath) {
        List<UserLog> userLogs = userLogDao.getLogsByUserId(userId);
        System.out.println("从数据库获取到 " + userLogs.size() + " 条日志");
        
        if (userLogs.isEmpty()) {
            System.out.println("警告：未从数据库获取到任何日志记录，用户ID: " + userId);
            return;
        }
        
        try (FileWriter writer = new FileWriter(filePath)) {
            for (UserLog userLog : userLogs) {
                if (userLog.getLogEntry() != null) {
                    writer.write(userLog.getLogEntry() + "\n");
                    System.out.println("写入日志: " + userLog.getLogEntry());
                } else {
                    System.err.println("警告：发现日志内容为 null，用户ID: " + userId + "，日志ID: " + userLog.getId());
                }
            }
            System.out.println("日志保存成功！");
        } catch (IOException e) {
            System.err.println("保存日志时出错: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 新增充值方法，添加充值日志
    public void recharge(int id, double amount) {
        User user = userDao.selectByPrimaryKey(id);
        if (user != null) {
            user.setBalance(user.getBalance() + amount);
            userDao.updateByPrimaryKeySelective(user);
            user.addLog("充值 " + amount + " 元，当前余额: " + user.getBalance());
            saveUserLogs(user);
        }
    }

    @Override
    public PageInfo<User> getAllUsersByPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> users = userDao.getAll();
        return new PageInfo<>(users);
    }
}